package com.bbs.core.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.alibaba.fastjson.JSONObject;
import com.bbs.core.common.Const;
import com.bbs.core.common.WebUtils;
import com.bbs.core.model.Module;
import com.bbs.core.model.Post;
import com.bbs.core.model.Topic;
import com.bbs.core.model.User;
import com.bbs.core.service.ModuleService;
import com.bbs.core.service.PostService;
import com.bbs.core.service.TopicService;

@Controller
public class TopicController {
	
	@Autowired
	private TopicService topicService;
	
	@Autowired
	private PostService postService;
	
	@Autowired
	private ModuleService moduleService;
	
	@Autowired
	WebUtils webUtils;
	
	@RequestMapping("/bbs/topic/hot")
	public RedirectView hotTopic(){
		return new RedirectView( "/bbs/topic/hot/1");
	}

	@RequestMapping("/bbs/topic/hot/{p}")
	public ModelAndView hotTopic(@PathVariable int p){
		 ModelAndView view = new ModelAndView();
		view.setViewName("/bbs/index.html");
		List<Topic> hotTopics = topicService.getHotTopics();
		view.addObject("topicPage", hotTopics);
		return view;
	}

	@RequestMapping("/bbs/topic/nice")
	public ModelAndView niceTopic(){
		return new ModelAndView( "forward:/bbs/topic/nice/1");
	}

	@RequestMapping("/bbs/topic/nice/{p}")
	public ModelAndView niceTopic(@PathVariable int p, ModelAndView view){
		view.setViewName("/bbs/index.html");
		List<Topic> niceTopics = topicService.getNiceTopics();
		view.addObject("topicPage", niceTopics);
		return view;
	}

	@RequestMapping("/bbs/topic/{id}-{p}.html")
	public ModelAndView topic(@PathVariable final int id, @PathVariable int p, HttpServletRequest request, HttpServletResponse response){
		ModelAndView view = new  ModelAndView();
		List<Module> modules = moduleService.findAllModules();
		List<Post> postsByTopicId = postService.getPostsByTopicId(id);
		Topic topic = topicService.getTopicByPrimaryKey(id);
		topic.setPv(topic.getPv() + 1);
		topicService.updateTopic(topic);
		User user = webUtils.currentUser(request, response);
		if(user != null){
			Integer mcount = topicService.queryMyMessageTopicCount(user.getId());
			view.addObject("mcount", mcount);
		}
		view.addObject("postPage", postsByTopicId);
		view.addObject("topic", topic);
		view.addObject("currentUser", user);
		view.setViewName("detail");
		view.addObject("modules", modules);
		view.addObject("currentUser", user);
		view.addObject("pagename", "首页综合");
		view.addObject("isAdmin", false);
		return view;
	}

	@RequestMapping("/bbs/topic/module/{id}-{p}.html")
	public ModelAndView module(@PathVariable final int id, @PathVariable int p){
		/*ModelAndView view = new ModelAndView();
		view.setViewName("/index.html");
		PageQuery query = new PageQuery(p, new HashMap(){{put("moduleId", id);}});
		query.setPageSize(Const.TOPIC_PAGE_SIZE);
		topicService.getTopics(query);
		view.addObject("topicPage", query);
		if(query.getList().size() >0){
			Topic bbsTopic = (Topic) query.getList().get(0);
			view.addObject("pagename",Topic.getTails().get("moduleName"));
		}*/
		return null;
	}

	@RequestMapping("/bbs/topic/add.html")
	public ModelAndView addTopic(ModelAndView view, HttpServletRequest request, HttpServletResponse response){
		User user = webUtils.currentUser(request, response);
		List<Module> modules = moduleService.findAllModules();
		view.addObject("modules", modules);
		view.addObject("currentUser", user);
		view.setViewName("post");
		return view;
	}

	/**
	 * 文章发布改为Ajax方式提交更友好
	 * @param topic
	 * @param post
	 * @param title
	 * @param postContent
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception 
	 */
	@ResponseBody
	@PostMapping("/bbs/topic/save")
	public JSONObject saveTopic(Topic topic, Post post, String title, String postContent,HttpServletRequest request, HttpServletResponse response) throws Exception{
		//@TODO， 防止频繁提交
		User user = webUtils.currentUser(request, response);
//		Date lastPostTime = bbsService.getLatestPost(user.getId());
//		long now = System.currentTimeMillis();
//		long temp = lastPostTime.getTime();
//		if(now-temp<1000*10){
//			//10秒之内的提交都不处理
//			throw new RuntimeException("提交太快，处理不了，上次提交是 "+lastPostTime);
//		}
		JSONObject result = new JSONObject();
		result.put("err", 1);
		if(user==null){
			result.put("msg", "请先登录后再继续！");
		}else if(title.length()<5||postContent.length()<10){
			//客户端需要完善
			result.put("msg", "标题或内容太短！");
		}else{
			topic.setIsNice("0");
			topic.setIsUp("0");
			topic.setPv(1);
			topic.setPostCount(1);
			topic.setReplyCount(0);
			post.setHasReply("0");
			topic.setContent(title);
			post.setContent(postContent);
			topicService.saveTopic(topic, post, user);
			
			result.put("err", 0);
			result.put("msg", "/bbs/topic/"+topic.getId()+"-1.html");
		}
		return result;
	}

}
